#!/usr/bin/perl
#Programmer: Rory Carmichael
#Purpose: Turn the histogram stats into handy dandy json format for use in google charts api
#Usage: stats2json.pl <histogram file>
#Stat json format
#Method	Val Weighted_Val

#Histogram Format
#depth actual min max 1st_quartile 2nd_quartile 3rd_quartile

sub print_json {
	my ($colref, $rowref, $roleref) = @_;
	my @cols = @$colref;
	my @rows = @$rowref;
	my %colroles = %$roleref;
	my $retval;
	my @types;

	$retval = "{\n\t\"cols\": [\n";
	foreach $col (@cols) {
		my ($label, $type) = split(/\t/, $col);
		push(@types,$type);
		if(!exists($colroles{$label})) {
			$retval .= "\t\t{\"id\":\"\",\"label\":\"$label\",\"pattern\":\"\",\"type\":\"$type\"},\n";
		} else {
			$retval .= "\t\t{\"id\":\"\",\"label\":\"$label\",\"pattern\":\"\",\"type\":\"$type\", \"p\":{\"role\":\"$colroles{$label}\"}},\n";
		}

	}
	$retval .= "\t],\n\t\"rows\": [\n";
	foreach my $row (@rows) {
		my @cells;
		my @splitrow = @$row;
		my $i=0;
		foreach my $cell (@$row) {
			if($types[$i] eq "string") {
				$cell = "\"$cell\"";
			}
			push(@cells, "{\"v\":$cell,\"f\":null}");
			$i++;
		}
		$retval .= "\t\t{\"c\":[" . join(",", @cells) . "]},\n";
	}
	$retval .= "\t]\n}\n";
	return $retval;
}

my $zero = 0.00001;
my $multiplier = 100/(log($zero)/log(10));
my $path = shift;
my $file = [split(/\//, $path)]->[-1];
my $prefix = [split(/\./, $file)]->[0];
my $hist_dir = ".";
my $stat_dir  = ".";
$hist_dir = shift if @_;
$stat_dir = shift if @_;

open(IF, "$path");

my @s_headers = split(/\s+/, <IF>);
my @s_vals = split(/\s+/, <IF>);
shift @s_headers;
my $cluster = shift @s_vals;
if($#s_vals != $#s_headers) {
	die("Headers and Values not Equal\n");
}

#populate json data for the radar plot
#methods are either weighted or unweighted, but we don't know the methods apriori
#all vals are of type number (in truth, they are all p-values)
my @radarheader = ( "method\tstring", "unweighted\tnumber", "weighted\tnumber" );
my @radardata;
my $lastrow;
my $i=0;
while($i<=$#s_vals) {
	#Can't take log of zero
	if($s_vals[$i] == 0) {
		$s_vals[$i] = $zero;
	}
	if($s_vals[$i+1] == 0) {
		$s_vals[$i+1] = $zero;
	}
	push(@radardata, [($s_headers[$i], $multiplier*log($s_vals[$i])/log(10), $multiplier*log($s_vals[$i+1])/log(10))]);
	$i+=2;
}

open(OF, ">$prefix.radar.jsonc");
print OF &print_json(\@radarheader, \@radardata);
close(OF);

#populate json data for the histogram plot
my @histheader = ( "depth\tstring","actual\tnumber", "min\tnumber", "q1\tnumber", "q3\tnumber", "max\tnumber", "q2\tnumber" );
my @histdata;
my %dhash;

#This works because real hist always comes before the mean boxes
my $real = 1;
while(my $line = <IF>) {
	chomp $line;
	if ($line !~ /:/) {
		my @splitline = split(/\s+/, $line);
		my $depth = shift @splitline;
		if($real == 1) {
			$dhash{$depth} = join("\t", $depth, shift(@splitline));
		} else {
			if (!exists($dhash{$depth})) {
				$dhash{$depth} = "$depth\t0";
			}
			#Need to reorder splitline to put median at back of list
			my $tmp = $splitline[2]; #grab median
			$splitline[2] = $splitline[3]; #put 3rd quart in median
			$splitline[3] = $splitline[4]; #put max in 3rd quart
			$splitline[4] = $tmp; #put median at end
			$dhash{$depth} = join("\t", $dhash{$depth}, @splitline);
		}
	} elsif ($line =~ /mean/) {
		$real = 0;
	}
}

foreach my $key (sort(keys(%dhash))) {
	push(@histdata, [ split(/\t/, $dhash{$key}) ]);
}

print join("\t", @histheader) . "\n";
foreach my $row (@histdata) {
	print join("\t", @$row) . "\n";
}

open(OF, ">$prefix.hist.jsonc");
print OF &print_json(\@histheader, \@histdata);
close(OF);

close(IF);
